package com.xyz.app.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.gson.reflect.TypeToken;
import com.xyz.app.inter.HtmlParser;

public class PornhubHtmlParser implements HtmlParser {

    private String host;

    public PornhubHtmlParser(String host) {
        this.host = host;
    }

    @Override
    public String getUrl(String url, int page) {
        if (url.contains("/player_related_datas")) {
            if (page > 0) {
                url = url + "/endDetail";
            }
        }
        page = page + 1;
        return url + "&page=" + page;
    }

    @Override
    public List<Map<String, String>> parseList(String rUrl, String content) {
        String ip = null;
        try {
            ip = new URL(rUrl).getHost();
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (rUrl.contains("/player_related_datas")) {
            if (rUrl.contains("/endDetail")) {
                return new ArrayList<Map<String, String>>();
            }
            return parseRelated(ip, content);
        }
        Document doc = Jsoup.parse(content);
        final List<Map<String, String>> mediaInfos = new ArrayList<Map<String, String>>(50);
        Elements elements = doc.select(".singleVideo");
        for (Element ele : elements) {
            try {
                Map<String, String> media = new HashMap<String, String>();
                Element e = ele.select("a").get(0);
                media.put("videoUri", e.attr("href"));
                media.put("link", "https://" + ip + e.attr("href"));
                media.put("relatedUrl", "https://" + host + e.attr("href"));
                media.put("linkHost", host);
                media.put("title", ele.select("img").get(0).attr("alt").replaceAll("([a-z0-9A-Z]*)\\.com", ""));
                String preview = ele.select("img").get(0).attr("data-src");
                media.put("preview", preview);
                media.put("duration", ele.select(".time").get(0).html());
                mediaInfos.add(media);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mediaInfos;
    }

    @SuppressWarnings("unchecked")
    private List<Map<String, String>> parseRelated(String ip, String content) {
        Map<String, Object> data = JsonUtil.json2object(content, new TypeToken<Map<String, Object>>() {
        });
        List<List<Object>> mostViewed = (List<List<Object>>) data.get("related");
        List<List<Object>> topRated = (List<List<Object>>) data.get("more");
        final List<Map<String, String>> mediaInfos = new ArrayList<Map<String, String>>(50);
        if (mostViewed == null) {
            mostViewed = new ArrayList<List<Object>>();
        }
        if (topRated != null) {
            mostViewed.addAll(topRated);
        }
        for (List<Object> item : mostViewed) {
            Map<String, String> media = new HashMap<String, String>();
            String url = item.get(4).toString();
            media.put("videoUri", url.substring(url.lastIndexOf("/")));
            media.put("link", url.replace(host, ip));
            media.put("relatedUrl", url);
            media.put("linkHost", host);
            media.put("title", item.get(1).toString().replaceAll("([a-z0-9A-Z]*)\\.com", ""));
            String preview = item.get(0).toString();
            media.put("preview", preview);
            media.put("duration", item.get(2).toString());
            mediaInfos.add(media);
        }
        return mediaInfos;
    }

    @Override
    public Map<String, String> parseDetail(String rUrl, String content) {
        Map<String, String> media = new HashMap<String, String>();
        content = content.split("flashvars_")[1];
        content = content.substring(content.indexOf("=") + 1, content.lastIndexOf("};") + 1);
        Map<String, Object> data = JsonUtil.json2object(content, new TypeToken<Map<String, Object>>() {
        });
        try {
            String relatedUrl = (String) data.get("related_url");
            media.put("relatedUrl", relatedUrl);
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> videoUrls = (List<Map<String, Object>>) data.get("mediaDefinitions");
            if (videoUrls != null) {
                String downloadUrl = null;
                for (Map<String, Object> videoUrl : videoUrls) {
                    if (videoUrl.get("videoUrl") != null && !videoUrl.get("videoUrl").equals("") && downloadUrl == null) {
                        downloadUrl = (String) videoUrl.get("videoUrl");
                    }
                    if (videoUrl.get("videoUrl") != null && !videoUrl.get("videoUrl").equals("")) {
                        media.put("videoUrl", (String) videoUrl.get("videoUrl"));
                    }
                }
                media.put("downloadUrl", downloadUrl);
            }
            media.put("downloadTitle", System.currentTimeMillis() + ".mp4");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return media;
    }

}
